package com.mjz.gui;

import javax.swing.*;
import javax.swing.table.DefaultTableModel;
import javax.swing.border.TitledBorder;
import java.awt.*;
import java.awt.event.ActionListener;
import java.sql.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import com.mjz.dao.Database;

public class CourseManageFrame extends JInternalFrame {

    private final JComboBox<String> teacherComboBox;
    private final JTable courseTable;
    private final JButton modifyCourseButton;
    private final JButton addCourseButton;

    public CourseManageFrame(JDesktopPane desktopPane) {
        super("课程管理", true, true, true, true);
        setSize(600, 400);
        setLocation((desktopPane.getWidth() - getWidth()) / 2, (desktopPane.getHeight() - getHeight()) / 2);
        setLayout(new GridBagLayout());

        GridBagConstraints gbc = new GridBagConstraints();
        gbc.insets = new Insets(5, 5, 5, 5);
        gbc.fill = GridBagConstraints.HORIZONTAL;

        // 第一行组件：教师姓名、修改课程、添加课程
        gbc.gridx = 0;
        gbc.gridy = 0;
        gbc.weightx = 0;
        add(new JLabel("教师姓名："), gbc);

        gbc.gridx = 1;
        gbc.weightx = 0.5;
        teacherComboBox = createTeacherComboBox();
        add(teacherComboBox, gbc);

        gbc.gridx = 2;
        gbc.weightx = 0.125;
        modifyCourseButton = new JButton("修改课程");
        add(modifyCourseButton, gbc);

        gbc.gridx = 3;
        gbc.weightx = 0.125;
        addCourseButton = new JButton("添加课程");
        add(addCourseButton, gbc);

        // 表格
        gbc.gridx = 0;
        gbc.gridy = 1;
        gbc.gridwidth = 4;
        gbc.fill = GridBagConstraints.BOTH;
        gbc.weightx = 1.0;
        gbc.weighty = 1.0;
        courseTable = new JTable();
        JScrollPane scrollPane = new JScrollPane(courseTable);
        add(scrollPane, gbc);

        populateCourseTable(null); // 初始加载所有课程
        setupButtonListeners();
    }


    private JComboBox<String> createTeacherComboBox() {
        JComboBox<String> comboBox = new JComboBox<>();
        comboBox.addItem("所有教师"); // 添加默认选项
        String sql = "SELECT name FROM teacher";
        try (Connection conn = Database.getConnection();
             Statement stmt = conn.createStatement();
             ResultSet rs = stmt.executeQuery(sql)) {
            while (rs.next()) {
                comboBox.addItem(rs.getString("name"));
            }
        } catch (SQLException ex) {
            JOptionPane.showMessageDialog(this, "数据库错误: " + ex.getMessage(), "错误", JOptionPane.ERROR_MESSAGE);
        }

        // 添加 ActionListener 来处理教师选择的变化
        comboBox.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                String selectedTeacher = (String) comboBox.getSelectedItem();
                populateCourseTable(selectedTeacher.equals("所有教师") ? null : selectedTeacher);
            }
        });

        return comboBox;
    }

    void populateCourseTable(String teacherName) {
        DefaultTableModel model = new DefaultTableModel(new String[]{"课程编号", "课程名称", "教师姓名", "最大人数", "已选人数", "信息"}, 0);
        String sql = "SELECT c.id, c.name, t.name, c.maxStuNum, c.selectedNum, c.info " +
                "FROM course c JOIN teacher t ON c.tid = t.id";
        if (teacherName != null) {
            sql += " WHERE t.name = ?";
        }
        try (Connection conn = Database.getConnection();
             PreparedStatement preparedStatement = conn.prepareStatement(sql)) {
            if (teacherName != null) {
                preparedStatement.setString(1, teacherName);
            }
            try (ResultSet rs = preparedStatement.executeQuery()) {
                while (rs.next()) {
                    model.addRow(new Object[]{
                            rs.getInt("id"),
                            rs.getString("name"),
                            rs.getString("t.name"),
                            rs.getInt("maxStuNum"),
                            rs.getInt("selectedNum"),
                            rs.getString("info")
                    });
                }
            }
        } catch (SQLException ex) {
            JOptionPane.showMessageDialog(this, "数据库错误: " + ex.getMessage(), "错误", JOptionPane.ERROR_MESSAGE);
        }
        courseTable.setModel(model);
    }

    private void setupButtonListeners() {
        modifyCourseButton.addActionListener(e -> {
            int selectedRow = courseTable.getSelectedRow();
            if (selectedRow == -1) {
                JOptionPane.showMessageDialog(this, "请选择要修改的课程!", "警告", JOptionPane.WARNING_MESSAGE);
                return;
            }
            Dialog dialog = new CourseDialog(this, "修改课程", true, courseTable, selectedRow);
            dialog.setVisible(true);
        });

        addCourseButton.addActionListener(e -> {
            Dialog dialog = new CourseDialog(this, "添加课程", true, courseTable, -1);
            dialog.setVisible(true);
        });
    }

    public void updateTeacherComboBoxSelection(String teacherName) {
        teacherComboBox.setSelectedItem(teacherName);
    }
}